import router from '@/router'
import { getToken } from '@/utils/auth'
import store from '@/store'
import { asyncRoutes } from './router/asyncRoutes'

// 处理一级路由权限数据
function getFirstRoutePerms(permsArr) {
  console.log('permsArr: ', permsArr)
  const newArr = permsArr.map(item => {
    return item.split(':')[0]
  })
  return [...new Set(newArr)]
}

// 处理二级路由权限数据
function getSecondRoutePerms(permsArr) {
  const secondArr = permsArr.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return [...new Set(secondArr)]
}

// 根据权限标识过滤路由表
function getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes) {
  if (firstRoutePerms.includes('*')) {
    // 管理员
    return asyncRoutes
  }
  // 根据一级和二级对动态路由表做过滤 return出去过滤之后的路由表
  // 1. 根据一级路由对动态路由表做过滤
  return asyncRoutes.filter(route => {
    return firstRoutePerms.includes(route.permission)
  }).map(item => {
    // 2. 对二级路由做过滤
    return {
      ...item,
      children: item.children.filter(item => secondRoutePerms.includes(item.permission))
    }
  })
}

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  const token = getToken()
  if (token) {
    next()
    if (!store.state.user.profile.id) {
      // 获取原始权限列表
      const permissions = await store.dispatch('user/getProfile')
      console.log(store.state.user.profile.permissions)
      const firstRoutePerms = getFirstRoutePerms(permissions)
      const secondRoutePerms = getSecondRoutePerms(permissions)
      const routes = getRoutes(firstRoutePerms, secondRoutePerms, asyncRoutes)
      routes.forEach(item => {
        router.addRoute(item)
      })
      // 渲染菜单
      store.commit('menu/setMenuList', routes)
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
